<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('标题')" prop="title">
            <el-input v-model="form.title" :placeholder="$t('标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('上市项目')" prop="listedId">
            <el-select v-model="form.listedId" clearable filterable :disabled="form.id!==undefined" :placeholder="$t('请选择')" @change="selectTree()">
              <el-option
                v-for="item in listedOptions"
                :key="item.id"
                :label="item.dealName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('证券代码')" prop="stockCode">
            <el-input v-model="form.stockCode" :placeholder="$t('证券代码')" disabled show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('我方持有总股数(万股)')" prop="shareHold">
            <Money v-model="form.shareHold" :placeholder="$t('我方持有总股数(万股)')" disabled @change="calcRateNotExceeding" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('持股比例(%)')" prop="shareRate">
            <Ratio v-model="form.shareRate" :placeholder="$t('持股比例(%)')" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('减持股数不超过(万股)')" prop="shareNotExceeding">
            <Money v-model="form.shareNotExceeding" :placeholder="$t('减持股数不超过(万股)')" @change="calcRateNotExceeding" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('减持比例不超过(%)')" prop="rateNotExceeding">
            <Money v-model="form.rateNotExceeding" :placeholder="$t('减持比例不超过(%)')" unit="rate" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计公告发布日期')" prop="releaseDate">
            <el-date-picker
              v-model="form.releaseDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('预计公告发布日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('交易方式')" prop="tradingWayArray">
            <el-checkbox-group v-model="form.tradingWayArray">
              <el-checkbox
                v-for="(dict, index) in tradingWayOptions"
                :key="index"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('预计减持日期')" prop="reducingDateArray">
            <DatePicker
              v-model="form.reducingDateArray"
              type="daterange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('公告内容')" prop="context">
            <el-input v-model="form.context" type="textarea" :placeholder="$t('公告内容')" show-word-limit maxlength="1000" />
          </el-form-item>
        </el-col>
      </el-row>
      <FileTable :list.sync="form.fileList" data-type="listed_reducing_notice" :btn-show="!otherBtnHide" :business-id="form.dealId" />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button v-if="form.actStatus !== 'D' && form.actStatus !== 'W' && !otherBtnHide" type="warning" plain :disabled="calcDisable" @click="measureCalc">{{ $t('点击测算') }}</el-button>
      <!--保存 取消按钮-->
      <FormBtn ref="formBtn" has-permi="listed:reducing" :bus-data="form" :btn-hide="btnHide" :menu-key="menuKey" style="display: inline-block;margin-left: 10px;" />
    </div>
    <!-- 上市项目A股测算页面 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpenA" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogFormPcwMedical" append-to-body>
      <listedMeasureA ref="listedMeasureA" />
    </el-dialog>
    <!-- 上市项目H股测算页面 -->
    <el-dialog :title="$t(title)" :visible.sync="formOpenH" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogFormPcwMedical" append-to-body>
      <listedMeasureH ref="listedMeasureH" />
    </el-dialog>
  </div>
</template>

<script>
import { saveListedReducingNotice, getListedReducingNotice } from '@/api/deal/listed/reducing/listedReducingNotice'
import { listListedDeal, getListedDeal } from '@/api/deal/listed/base/listedDeal'
import listedMeasureA from './listedMeasureA.vue'
import listedMeasureH from './listedMeasureH.vue'
import moment from 'moment'

export default {
  components: {
    listedMeasureA,
    listedMeasureH
  },
  data() {
    return {
      // 菜单标识
      menuKey: 'listed_reducing_notice',
      // 表单参数
      form: {
        reducingDateArray: [],
        tradingWayArray: [],
        fileList: []
      },
      // 是否隐藏保存按钮
      btnHide: false,
      // 是否隐藏其它按钮
      otherBtnHide: true,
      // 遮罩层
      loading: false,
      // 弹窗标题
      title: '',
      // 是否弹窗A股测算页面
      formOpenA: false,
      // 是否弹窗H股测算页面
      formOpenH: false,
      // 上市项目options
      listedOptions: [],
      // 表单校验
      rules: {
        title: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        listedId: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        shareHold: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        shareRate: [{ required: true, message: this.$t('必填信息'), trigger: 'change' }],
        shareNotExceeding: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        releaseDate: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }],
        reducingDateArray: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }],
        tradingWayArray: [{ required: true, message: this.$t('必填信息'), trigger: ['blur', 'change'] }]
      },
      // 交易方式字典
      tradingWayOptions: [],
      // 上市项目查询条件
      listedQueryParam: {},
      // 测算按钮置灰状态
      calcDisable: true
    }
  },
  watch: {
    form: {
      handler() {
        if (this.form.listedId !== undefined && this.form.releaseDate !== undefined && this.form.rateNotExceeding !== undefined && this.form.rateNotExceeding !== '') {
          this.calcDisable = false
        } else {
          this.calcDisable = true
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.$bus.$emit('async_done')
  },
  created() {
    this.getDicts('listed_trading_way').then(response => {
      this.tradingWayOptions = response.data
    })
    this.listedQueryParam.dealType = (this.$route.query.dealType === undefined ? 'equity' : this.$route.query.dealType)
    listListedDeal(this.listedQueryParam).then(response => {
      this.listedOptions = response.rows
    })
  },
  methods: {
    // 初始化数据
    init(data) {
      if (data != null && data.id !== undefined) {
        getListedReducingNotice(data.id).then(response => {
          this.form = response.data
          // 设置交易方式
          if (this.form.tradingWay !== null && this.form.tradingWay !== '') {
            var arr = this.form.tradingWay.split(',')
            this.$set(this.form, 'tradingWayArray', arr)
          }
          // 设置减持日期区间
          this.form.reducingDateArray = []
          this.form.reducingDateArray[0] = this.form.reducingDateStart
          this.form.reducingDateArray[1] = this.form.reducingDateEnd
          // 获取项目相关数据
          this.selectTree()
        })
      } else {
        this.reset()
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        listedId: undefined,
        dealName: undefined,
        stockCode: undefined,
        shareHold: undefined,
        shareRate: undefined,
        dealType: (this.$route.query.dealType === undefined ? 'equity' : this.$route.query.dealType),
        title: undefined,
        shareNotExceeding: undefined,
        rateNotExceeding: undefined,
        releaseDate: undefined,
        tradingWay: undefined,
        reducingDateStart: undefined,
        reducingDateEnd: undefined,
        context: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        delFlag: undefined,
        remark: undefined,
        tradingWayArray: [],
        fileList: []
      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      this.$parent.$parent.reset()
    },
    // 选择上市项目事件，获取选择的项目的其他关联数据
    selectTree() {
      // 获取关联数据
      getListedDeal(this.form.listedId).then(res => {
        if (this.form.actStatus !== 'W') {
          this.otherBtnHide = false
        }
        this.form.stockCode = res.data.stockCode
        this.form.shareHold = res.data.shareHold
        this.form.shareRate = res.data.shareRate
        this.form.totalEquity = res.data.totalEquity
        this.form.dealId = res.data.dealId
        this.form.dealName = res.data.dealName
        this.form.market = res.data.market
        this.calcRateNotExceeding()
      })
    },
    // 计算减持比例不超过百分比 = 减持股数 / 总股本
    calcRateNotExceeding() {
      if (this.form.totalEquity !== undefined && this.form.shareNotExceeding && this.form.totalEquity !== 0) {
        this.form.rateNotExceeding = (this.form.shareNotExceeding / this.form.totalEquity * 100).toFixed(4)
      }
    },
    // 打开测算页面
    measureCalc() {
      // 判断当前上市项目为A股还是H股
      if (this.form.market === 'GANGGU') {
        // 打开H股测算页面
        this.title = this.form.dealName + '-H股'
        this.formOpenH = true
        this.$nextTick(() => {
          this.$refs.listedMeasureH.queryParams.listedId = this.form.listedId
          this.$refs.listedMeasureH.listedId = this.form.listedId
          this.$refs.listedMeasureH.queryParams.noticeDate = this.parseTime(this.form.releaseDate)
          this.$refs.listedMeasureH.queryParams.rateNotExceeding = this.form.rateNotExceeding
          this.$refs.listedMeasureH.init()
          this.$refs.listedMeasureH.getCheckH()
        })
      } else {
        // 打开A股测算页面
        this.title = this.form.dealName + '-A股'
        this.formOpenA = true
        this.$nextTick(() => {
          this.$refs.listedMeasureA.queryParams.listedId = this.form.listedId
          this.$refs.listedMeasureA.listedId = this.form.listedId
          this.$refs.listedMeasureA.queryParams.noticeDate = this.parseTime(this.form.releaseDate)
          this.$refs.listedMeasureA.queryParams.rateNotExceeding = this.form.rateNotExceeding
          this.$refs.listedMeasureA.init()
          this.$refs.listedMeasureA.getCheckA()
        })
      }
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm: function(type) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate(valid => {
          if (valid) {
            this.loading = true
            // 设置减持日期区间值
            if (this.form.reducingDateArray !== undefined) {
              if (this.form.reducingDateArray[0] !== null && this.form.reducingDateArray[0] !== undefined) {
                this.form.reducingDateStart = moment(this.form.reducingDateArray[0]).format('YYYY-MM-DD')
              }
              if (this.form.reducingDateArray[1] !== null && this.form.reducingDateArray[1] !== undefined) {
                this.form.reducingDateEnd = moment(this.form.reducingDateArray[1]).format('YYYY-MM-DD')
              }
            }
            // 设置交易方式值
            if (this.form.tradingWayArray !== undefined) {
              var way = ''
              this.form.tradingWayArray.forEach(item => {
                way += ',' + item
              })
              this.form.tradingWay = way.substring(1)
            }
            saveListedReducingNotice(this.form).then(response => {
              if (response.code === 200) {
                if (type === 'process') {
                  // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                  this.form.id = response.data
                  // 启动流程
                  this.startProcess(response.data)
                } else {
                  this.msgSuccess(this.$t('保存成功'))
                  this.closeForm()
                }
                resolve()
              } else {
                this.msgError(response.msg)
                this.loading = false
                reject()
              }
              this.loading = false
            })
          } else {
            reject()
            this.locationError(document)
          }
        })
      })
    },
    // 启动流程
    startProcess: function(dataId) {
      this.loading = false
      // 启动流程时候传入的参数
      const processData = {}
      // 待办标题
      processData.title = this.form.dealName + ' - ' + this.form.title
      // 业务表名
      processData.dataTable = 'listed_reducing_notice'
      // 业务ID
      processData.dataId = dataId
      // 业务表单地址
      processData.formPath = '@/views/deal/listed/reducing/listedReducingNoticeForm'
      processData.viewPath = '@/views/deal/listed/reducing/listedReducingNoticeView'
      // 菜单标识(根据菜单标识判断的走哪个流程)
      processData.menuKey = this.menuKey
      this.startProcessByMenu(processData, () => {
        this.form.actStatus = 'D'
        this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
        this.closeForm()
      })
    }
  }
}
</script>
